package submit

import (
	"bytes"
	"encoding/json"
	"fmt"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/service-center-client/service/discover"
	"gitee.com/zaper/service-center-client/service/service_info"
	"gitee.com/zaper/service-config-client/os_env"
	"gitee.com/zaper/software-framework/constant"
	fmkutil "gitee.com/zaper/software-framework/util"
	"math/rand"
	"os"
)

var (
	submitInterface = "/api/v1/config/submit"
)

func SubmitStatus(uuid, configName string) bool {
	center := discover.GetDiscoverClientManager()
	instances := center.GetServiceInfo("service-config")
	var instance service_info.InstanceInfo
	if len(instances) <= 0 {
		return false
	}
	instance = instances[rand.Intn(len(instances))]
	httpClient := fmkutil.NewHttpClientManager()
	url := fmt.Sprintf("%s%s%s", "https://", instance.Endpoints[rand.Intn(len(instance.Endpoints))],
		submitInterface)
	message := &SubmitModel{
		UUID:       uuid,
		ConfigName: configName,
		ServiceId:  os.Getenv(os_env.ServiceIdKey),
	}
	result, err := json.Marshal(message)
	if err != nil {
		logger.Printf("submit status fail,Marshal request fail ")
		return false
	}
	_, err = httpClient.Post(url, constant.ContentType, bytes.NewReader(result))
	if err != nil {
		logger.Printf("request fail")
		return false
	}
	logger.Println("result success")
	return true
}
